<template>
  <div>
    <!--    <hte-file-class-form ref="realForm" @ok="submitCallback" :disabled="disableSubmit"></hte-file-class-form>-->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button icon="sync" @click="loadRange(hteFile)" v-if="hteFile.id">刷新</a-button>
      <a-button icon="plus" @click="handleAdd" v-if="hteFile.id">添加共享</a-button>
      <a-button icon="delete" @click="handleDel" v-if="hteFile.id">删除</a-button>
      <a-button icon="setting" @click="handleSendYami(1)" v-if="hteFile.id">设置发送娅米消息</a-button>
      <a-button icon="delete" @click="handleSendYami(0)" v-if="hteFile.id">取消发送娅米消息</a-button>
      <!-- <FileShareForm :fileId="hteFile.id"/>
      <FileShareForm :fileId="hteFile.id" type="text"/>
      <FileShareForm :fileId="hteFile.id" type="icon"/> -->
    </div>
    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        row-key="id"
        :columns="columns"
        :data-source="tableData"
        :pagination="ipagination"
        :loading="loading"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      />
    </div>

    <!-- <a-modal
      title="添加共享范围"
      :width="700"
      :visible="addVisible"
      :confirm-loading="confirmLoading"
      @ok="handleAddOk"
      @cancel="handleAddCancel"
      :maskClosable="false"
    >
      <a-form-model ref="form" :model="model" :rules="validatorRules" style="width: 600px">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="对象类型：" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-radio-group
                v-model="model.objectType"
                name="radioGroup"
                :default-value="1"
                @change="handleObjectChange"
              >
                <a-radio :value="1"> 私有组 </a-radio>
                <a-radio :value="2"> 发送人员 </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="对象名称" :label-col="labelCol" :wrapper-col="wrapperCol" prop="objectId">
              <a-select
                ref="selectRef"
                v-model="model.objectId"
                mode="multiple"
                placeholder="请输入对象名称"
                style="width: 100%"
                :filter-option="false"
                :not-found-content="fetching ? '找不到记录' : null"
                @search="fetchObj"
                @change="selectObjectChange"
              >
                <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                <a-select-option v-for="d in objData" :key="d.value" :value="d.value">
                  {{ d.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="权限" :label-col="labelCol" :wrapper-col="wrapperCol" prop="authority">
              <a-select v-model="model.authority" mode="multiple" placeholder="请选择权限">
                <a-select-option
                  v-for="option in authorityOptions"
                  :key="'auth' + option.value"
                  :value="option.value"
                  :defaultValue="[1]"
                  :disabled="option.disabled"
                  >{{ option.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

        </a-row>
      </a-form-model>
    </a-modal> -->
    <file-range-add :visible="addVisible" :saveData='tableData' :fileType="hteFile.fileType" ref="fileRangeAdd" @handleAddCancel='handleAddCancel' @handleAddOk="handleAddOk"></file-range-add>
  </div>
</template>

<script>
import { postAction, getAction } from '@/api/manage'
import FileRangeAdd from '@/views/library/modules/FileRangeAdd'
export default {
  name: 'FileRange',
    components: {
    FileRangeAdd,
    // FileShareForm: () => import('@/views/library/components/FileShareForm')
  },
  props: {
    hteFile: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      authorityOptions: [
        // { value: '1', label: '查阅', disabled: false },
        // { value: '2', label: '编辑', disabled: false },
        // { value: '3', label: '下载', disabled: false },
        // { value: '4', label: '可废除', disabled: false },
        // { value: '5', label: '一级发布', disabled: true },
      ],
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '对象类型 ',
          align: 'center',
          dataIndex: 'objectType',
          customRender: (text) => {
            if (text == 1) {
              return '私有组';
            } else if (text == 2) {
              return '发送人员';
            }else if (text == 3) {
              return '组织架构';
            }
            else if (text == 4) {
              return '所有人公开';
            }
            return text
          },
        },

        {
          title: '对象名称',
          align: 'center',
          dataIndex: 'objectName',
        },
        {
          title: '共享类型 ',
          align: 'center',
          dataIndex: 'shareType',
          customRender: (text) => {
            if (text == 1) {
              return '默认共享'
            } else if (text == 2) {
              return '文件共享'
            } else if (text == 3) {
              return '分发共享'
            }
            return text
          },
        },
        {
          title: '权限',
          align: 'center',
          dataIndex: 'authority',
          customRender: (text) => {
            var str = ''
            if (text && text.indexOf('1') >= 0) {
              str += '查阅,'
            }
            if (text && text.indexOf('2') >= 0) {
              str += '编辑,'
            }
            if (text && text.indexOf('3') >= 0) {
              str += '下载,'
            }
            if (text && text.indexOf('4') >= 0) {
              str += '可废除,'
            }
            if (text && text.indexOf('5') >= 0) {
              str += '一级发布,'
            }
            if (str.length > 1) {
              return str.substr(0, str.length - 1)
            }
            return str
          },
        },
        {
          title: '发送亚米消息',
          align: 'center',
          dataIndex: 'sendYami',
          customRender: (text) => {
            if (text == 1) {
              return '是'
            } else if (text == 0){
              return '否'
            } else{
              return ''
            }
            return text
          },
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createUserName',
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
        },
        {
          title: '客户端',
          align: 'center',
          dataIndex: 'client',
        },
      ],
      tableData: [],
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        name: '',
      },
      loading: false,
      title: '',
      width: 800,

      disableSubmit: false,
      data: [],
      selectedRowKeys: [],
      rowKeyIndex: -1,
      addVisible: false,
      confirmLoading: false,
      model: { objectType: 1, client: '海芯', objectId: [] },
      validatorRules: {
        authority: [{ required: true, message: '请选择权限' }],
        objectId: [{ required: true, message: '请输入选择' }],
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      objData: [],
      fetching: false,
      url: {
        save: '/lib/hteLibFileRange/add',
        list: '/lib/hteLibFileRange/list',
        deleteBatch: '/lib/hteLibFileRange/deleteBatch',
        getUserList: '/lib/hteFileClass/getUserList',
        getGroupList: '/lib/hteLibraryGroup/groupList',
        getClassAuthority: '/lib/hteFileClass/getClassAuthority',
        sendYami: '/lib/hteLibFileRange/sendYami',
      },
    }
  },

  created() {
    // this.loadRange()
  },
  methods: {
    handleAdd() {
      this.addVisible = true
      this.model = { objectType: 1, client: '海芯', objectId: [] }
    },
    handleAddOk(data) {
    
        data.fileId = this.hteFile.id;
      
      postAction(this.url.save, data).then((res) => {
            if (res.success) {
              
              this.loadRange(this.hteFile)
              this.handleAddCancel();
            }
          })
    },
    handleAddCancel() {
      this.addVisible = false
    },
    loadRange() {
      let param = Object.assign({}, this.ipagination)
      param.classId = this.hteFile.fileType
      delete param.pageSizeOptions
      delete param.showTotal
      let fileId = this.hteFile.id ? this.hteFile.id : 0
      getAction(this.url.list + '/' + fileId, param).then((res) => {
        if (res.success) {
          if (res.result.total) {
            this.$set(this.ipagination, 'total', res.result.total)
          } else {
            this.$set(this.ipagination, 'total', 0)
          }
          this.tableData = res.result.records
           this.$emit("getTotal",this.ipagination.total)
        }
      })
      if (this.hteFile.fileType) {
        getAction(this.url.getClassAuthority, { id: this.hteFile.fileType }).then((res) => {
          if (res.success) {
            this.authorityOptions = res.result
          }
        })
      }
    },
    handleSave() {
      const that = this
      this.data.forEach((it, index) => {
        it.fileId = this.hteFile.id
      })
      postAction(this.url.save, this.data).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleDel() {
      var that = this
      var pass = 1
      debugger
      this.selectedRowKeys.forEach((it) => {
        const rowData = that.tableData.find((v) => v.id === it)
        if (!!rowData && rowData.shareType === 1) {
          pass = 0
        }
      })
      if (pass == 0) {
        that.$message.error('默认共享不能删除')
        return false
      }
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中数据?',
        onOk: function () {
          let ids = ''
          that.selectedRowKeys.forEach((key) => {
            if (key > 0) {
              ids += key + ','
            }
            const index = that.tableData.findIndex((v) => v.id === key)
            that.tableData.splice(index, 1)
          })
          getAction(that.url.deleteBatch, { ids: ids }).then((res) => {
            if (res.success) {
              that.selectedRowKeys = []
              that.loadRange(this.hteFile)
            } else {
              that.$message.warning(res.message)
            }
          })
        },
      })
    },
    handleSendYami(type) {
      var that = this
      var pass = 1
      debugger
      this.selectedRowKeys.forEach((it) => {
        const rowData = that.tableData.find((v) => v.id === it)
        if (!!rowData && rowData.objectType != 2) {
          pass = 0
        }
      })
      if (pass == 0) {
        that.$message.error('非发送人员不能设置发送亚米消息')
        return false
      }
      let content = '确认将选择的人员设置为发送娅米消息'
      if(type==0){
        content = '确认将选择的人员取消为发送娅米消息'
      }
      this.$confirm({
        title: '设置亚米消息提醒',
        content: content,
        onOk: function () {
          let ids = ''
          that.selectedRowKeys.forEach((key) => {
            if (key > 0) {
              ids += key + ','
            }
            const index = that.tableData.findIndex((v) => v.id === key)
            that.tableData.splice(index, 1)
          })
          postAction(that.url.sendYami+"?type="+type+"&fileId="+that.hteFile.id, that.selectedRowKeys).then((res) => {
            if (res.success) {
              that.selectedRowKeys = []
              that.loadRange(that.hteFile)
            } else {
              that.$message.warning(res.message)
            }
          })
        },
      })
    },
    
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    fetchObj(val) {
      this.objData = []
      this.fetching = true
      let url = this.url.getGroupList
      if (this.model.objectType === 2) {
        url = this.url.getUserList
      }
      getAction(url, { name: val }).then((res) => {
        if (res.success) {
          this.objData = res.result
          if (res.result.length > 0) {
            this.fetching = false
            if (this.model.objectType == 2) {
              res.result.forEach((it) => {
                this.objData.push({ label: it.realname, value: it.username })
              })
            } else {
              res.result.forEach((it) => {
                this.objData.push({ label: it.name, value: it.id })
              })
            }
          }
        }
      })
    },
    handleTableChange(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      if (Object.keys(sorter).length > 0) {
        this.$set(this.isorter, 'column', sorter.field)
        this.$set(this.isorter, 'order', sorter.order === 'ascend' ? 'asc' : 'desc')
      }
      this.ipagination = pagination
      this.$set(this.ipagination, 'pageNo', this.ipagination.current)
      this.loadRange(this.hteFile)
    },
    handleObjectChange() {
      this.$set(this.model, 'objectId', [])
      this.$set(this.model, 'authority', [])
      this.objData = []
      const forwardOption = this.authorityOptions.find((value) => value.value === '5')
      if (forwardOption && this.model.objectType === 1) {
        this.$set(forwardOption, 'disabled', true)
      } else if (forwardOption) {
        this.$set(forwardOption, 'disabled', false)
      }
    },
    selectObjectChange(){
      this.$refs.selectRef.blur()
    }
  },
  watch: {
    'hteFile.fileType': {
      handler: function (newVal, oldVal) {
        if (newVal != oldVal) {
          this.loadRange()
        }
      },
    },
    'hteFile.id': {
      handler: function (newVal, oldVal) {
        if (newVal != oldVal) {
          this.loadRange()
        }
      },
    },
  },
}
</script>
